package com.ruoyi.web.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.web.entity.CaseInfoEntity;
import lombok.Data;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：wang.j.f
 * @description：
 * @date ：Created in 2021/6/20 11:20
 * @modified By：
 * @version: 1.0$
 */
@Data
public class CaseInfoExcelListener extends AnalysisEventListener<CaseInfoEntity> {

    private ThreadLocal<List<CaseInfoEntity>> localCaseInfos = new ThreadLocal<>();

    // 实际上报数
    private Integer actualReportNum = 0;

    // 有效上报数
    private Integer effectiveReportNum = 0;

    // 已结案案件数量
    private Integer closedReportNum = 0;

    // 处理中案件数量
    private Integer processingReportNum = 0;

    // 作废案件数量
    private Integer invalidReportNum = 0;

    private Map<String, Long> smallClassAgg = new LinkedHashMap<>();



    @Override
    public void invoke(CaseInfoEntity caseInfoEntity, AnalysisContext analysisContext) {
        List<CaseInfoEntity> caseInfoEntities = localCaseInfos.get();
        if (caseInfoEntities == null) {
            caseInfoEntities = new ArrayList<CaseInfoEntity>();
        }
        // 实际上报数
        if (!"作废".equals(caseInfoEntity.getStatus())) {
            this.effectiveReportNum ++;
        } else {
            // 作废数量
            this.invalidReportNum ++;
        }
        if ("已结案".equals(caseInfoEntity.getStatus())) {
            this.closedReportNum ++;
        }
        if ("处理中".equals(caseInfoEntity.getStatus())) {
            this.processingReportNum ++;
        }
        caseInfoEntities.add(caseInfoEntity);
        localCaseInfos.set(caseInfoEntities);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<CaseInfoEntity> caseInfoEntities = localCaseInfos.get();
        this.setActualReportNum(caseInfoEntities.size());
        // 按照小类分组排序
        caseInfoEntities
                .stream()
                // 按照小类分类分组count
                .collect(Collectors.groupingBy(CaseInfoEntity::getSmallClass, Collectors.counting()))
                .entrySet().stream()
                // 根据count值倒序排序
                .sorted((p1, p2) -> -p1.getValue().compareTo(p2.getValue()))
                .collect(Collectors.toList()).forEach(ele -> smallClassAgg.put(ele.getKey(), ele.getValue()));

    }
}
